using ClosedXML.Excel;
using System.Data;

namespace ReadAPI.Utils
{
    public static class ExcelHelper
    {
        /// <summary>
        /// 将DataTable转换为Excel字节数组
        /// </summary>
        /// <param name="dt">DataTable数据</param>
        /// <returns>Excel文件的字节数组</returns>
        public static byte[] DataTableToExcel(DataTable dt)
        {
            using var workbook = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add(dt.TableName);

            // 添加列头
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cell(1, i + 1).Value = dt.Columns[i].ColumnName;
            }

            // 添加数据行
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    worksheet.Cell(i + 2, j + 1).Value = dt.Rows[i][j]?.ToString() ?? "";
                }
            }

            // 自动调整列宽
            worksheet.Columns().AdjustToContents();

            // 将工作簿转换为字节数组
            using var stream = new MemoryStream();
            workbook.SaveAs(stream);
            return stream.ToArray();
        }
    }
}